package com.zyh.utils;
import java.sql.Connection;
import java.sql.SQLException;

public class TransactionManager {

    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();

    public static Connection getCurrentConnection() throws SQLException {
        Connection conn = THREAD_LOCAL.get();
        if (conn == null || conn.isClosed()) {
            conn = JdbcUtils.getConnection();
            THREAD_LOCAL.set(conn);
        }
        return conn;
    }

    public static void beginTransaction() throws SQLException {
        getCurrentConnection().setAutoCommit(false);
    }

    public static void commit() throws SQLException {
        Connection conn = THREAD_LOCAL.get();
        if (conn != null) conn.commit();
    }

    public static void rollback() throws SQLException {
        Connection conn = THREAD_LOCAL.get();
        if (conn != null) conn.rollback();
    }

    public static void release() throws SQLException {
        Connection conn = THREAD_LOCAL.get();
        if (conn != null) {
            conn.setAutoCommit(true);
            JdbcUtils.releaseConnection(conn);
            THREAD_LOCAL.remove();
        }
    }
}
